<template>
  <div class="app-container">
    <div>
      <el-form
        ref="form"
        label-width="130px"
        label-position="right"
        size="small"
        :rules="rules"
        :model="psswordForm"
      >
        <el-form-item
          class="form-content"
          size="small"
          label="旧密码："
          prop="oldPwd"
        >
          <el-input
            v-model="psswordForm.oldPwd"
            placeholder="请输入旧密码"
          ></el-input>
        </el-form-item>
        <el-form-item
          class="form-content"
          style="margin-top: 25px"
          size="small"
          label="新密码："
          prop="newPwd"
        >
          <el-input
            v-model="psswordForm.newPwd"
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item
          class="form-content"
          style="margin-top: 25px"
          size="small"
          label="确认新密码："
          prop="surePwd"
        >
          <el-input
            v-model="psswordForm.surePwd"
            placeholder="请确认新密码"
          ></el-input>
        </el-form-item>
        <el-form-item class="form-content" style="margin-top: 25px">
          <el-button
            class="button-sure"
            size="small"
            type="primary"
            :loading="summitBtnLoading"
            @click="onSureClick"
            >确认修改</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UpdatePassword',
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能少于6位'))
      } else if (value != this.psswordForm.newPwd) {
        callback(new Error('两次密码输入不一致'))
      } else {
        callback()
      }
    }
    return {
      summitBtnLoading: false,
      psswordForm: { oldPwd: '', newPwd: '', surePwd: '' },
      rules: {
        oldPwd: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
        newPwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          {
            pattern: /^(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]{6,20}$/,
            message: '必须含有数字、字母、特殊符号三项中间的两项,6到20位',
          },
        ],
        surePwd: [
          { required: true, trigger: 'blur', validator: validatePassword },
        ],
      },
    }
  },
  mounted() {},
  methods: {
    onSureClick() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.logout()
        } else {
          return false
        }
      })
    },
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login?redirect=${this.$route.fullPath}`)
    },
  },
}
</script>

<style lang="scss" scoped>
.app-container {
  .form-content {
    margin-top: 50px;
    margin-left: 100px;
    width: 500px;
    .button-sure {
      width: 100px;
    }
  }
}
</style>
